package com.element.security.single.token;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisTokenStore {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public <T> T get(String key, Class<T> clazz) {
        String value = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.hasText(value)) {
            return null;
        }
        return deserialize(value, clazz);
    }

    public <T> void put(String key, T value, long expires) {
        if (null == value) {
            return;
        }
        String serialize = serialize(value);
        stringRedisTemplate.opsForValue().set(key, serialize, expires, TimeUnit.SECONDS);
    }

    public Long getExpires(String key) {
        return stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    private  <T> String serialize(T value) {
        if (null == value) {
            return null;
        }
        return JSON.toJSONString(value, SerializerFeature.WriteClassName);
    }

    private <T> T deserialize(String value, Class<T> clazz) {
        if (!StringUtils.hasText(value)) {
            return null;
        }
        return JSON.parseObject(value, clazz);
    }
}